﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Runtime.InteropServices;
using System.Configuration;
using System.Text.RegularExpressions;

namespace Common
{
    public class GetMes
    {
        /// <summary>
        /// 返回本页指定的get参数
        /// </summary>
        /// <param name="strRequest">请求对象</param>
        /// <param name="strKey">键值</param>
        /// <returns></returns>
        public static string GetRequestQuery(HttpRequest strRequest, string strKey)
        {
            return (strRequest.QueryString[strKey] != null) ? strRequest.QueryString[strKey].ToString() : "";
        }

        /// <summary>
        /// 返回本页指定的post参数
        /// </summary>
        /// <param name="strRequest">请求对象</param>
        /// <param name="strKey">键值</param>
        /// <returns></returns>
        public static string GetRequestForm(HttpRequest strRequest, string strKey)
        {
            return (strRequest.Form[strKey] != null) ? strRequest.Form[strKey].ToString() : "";
        }
        /// <summary>
        /// 根据会话的键值 获取会话值(根据同名cookie检测，若cookie存在，重新写入session)
        /// </summary>
        /// <param name="strKey"></param>
        /// <returns></returns>
        public static string GetSessionByCookie(string strKey)
        {
            string strUserID = (HttpContext.Current.Session[strKey] != null) ? HttpContext.Current.Session[strKey].ToString() : "";
            if (string.IsNullOrEmpty(strUserID))
            {
                // 检测指定cookies里是否有值 是则新建session 否则 返回空
                if (!string.IsNullOrEmpty(GetCookies(strKey)))
                {
                    SetMes.SetSession(strKey, Common.EncryptString.DeMyEnncrypt(GetCookies(strKey), 6));
                    strUserID = HttpContext.Current.Session[strKey].ToString();
                }
                else
                {
                    strUserID = "";
                }
            }
            return strUserID;
        }
        /// <summary>
        /// 根据会话的键值 获取会话值
        /// </summary>
        /// <param name="strKey"></param>
        /// <returns></returns>
        public static string GetSession(string strKey)
        {
            return (HttpContext.Current.Session[strKey] != null) ? HttpContext.Current.Session[strKey].ToString() : "";
            
        }
        /// <summary>
        /// 核对验证码
        /// </summary>
        /// <param name="strCheckKey">验证码的session键值</param>
        /// <param name="strInPut">用户输入的字符</param>
        /// <returns></returns>
        public static bool GetCheckResult(string strCheckKey, string strInPut)
        {
            if (GetSession(strCheckKey.ToLower()).Equals(strInPut.ToLower()))
            {
                return true;
            }
            return false;
        }
        /// <summary>
        /// 获取指定键值的cookies值
        /// </summary>
        /// <param name="strKey"></param>
        /// <returns></returns>
        public static string GetCookies(string strKey)
        {
            return (HttpContext.Current.Request.Cookies[strKey] != null) ? HttpContext.Current.Request.Cookies[strKey].Value : "";
        }


        /// <summary>
        /// 属性 获取SessionID
        /// </summary>
        public static string session_ID
        {
            get
            {
                if (!string.IsNullOrEmpty(System.Web.HttpContext.Current.Session.SessionID) && (System.Web.HttpContext.Current.Session.SessionID).Trim() != "")
                {
                    return System.Web.HttpContext.Current.Session.SessionID;
                }
                else
                {
                    return "";
                }
            }
        }

        /// <summary>
        /// 返回指定位数的随机数
        /// </summary>
        /// <param name="strNum">指定位数...</param>
        /// <returns></returns>
        public static string GetRandomNum(int strNum)
        {
            Random ran = new Random();
            return ran.Next(Convert.ToInt32(Math.Pow(10, strNum))).ToString();
        }
        /// <summary>
        /// 产生随机数
        /// </summary>
        /// <param name="min"></param>
        /// <param name="max"></param>
        /// <returns></returns>
        public static int Random(int min, int max)
        {
            Random num = new Random();
            return num.Next(min, max);
        }
        /// <summary>
        /// 取得IP地址
        /// </summary>
        /// <returns></returns>
        public static string GetIp()
        {
            string str = "";
            //穿过代理服务器取远程用户真实IP地址：
            if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
                str = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
            else
                str = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
            return str;
        }

        /// <summary>
        /// 截取字符串，中文安两个字符处理
        /// </summary>
        /// <param name="stringToSub"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string GetFirstString(object stringToSub, int length)
        {
            Regex regex = new Regex("[\u4e00-\u9fa5]+", RegexOptions.Compiled);
            char[] stringChar = stringToSub.ToString().ToCharArray();
            StringBuilder sb = new StringBuilder();
            int nLength = 0;
            for (int i = 0; i < stringChar.Length; i++)
            {
                if (regex.IsMatch((stringChar[i]).ToString()))
                {
                    sb.Append(stringChar[i]);
                    nLength += 2;
                }
                else
                {
                    sb.Append(stringChar[i]);
                    nLength = nLength + 1;
                }

                if (nLength > length)
                {
                    break;
                }
            }
            return sb.ToString();
        }


        [DllImport("Iphlpapi.dll")]
        private static extern int SendARP(Int32 dest, Int32 host, ref Int64 mac, ref Int32 length);
        [DllImport("Ws2_32.dll")]
        private static extern Int32 inet_addr(string ip);
        /// <summary>
        /// 获取客户机MAC地址  根据IP地址 获取机器的MAC地址
        /// </summary>
        /// <returns></returns>
        public static string GetBarMACIP(string strIP)
        {
            //MAC信息
            string mac_dest = "";
            try
            {
                int ldest = inet_addr(strIP); //目的地的ip 
                int lhost = inet_addr("");   //本地服务器的ip 
                Int64 macinfo = new Int64();
                int len = 6;
                int res = SendARP(ldest, 0, ref macinfo, ref len);
                string mac_src = macinfo.ToString("X");
                if (mac_src == "0")
                {
                    return "1";
                }
                while (mac_src.Length < 12)
                {
                    mac_src = mac_src.Insert(0, "0");
                }

                for (int i = 0; i < 11; i++)
                {
                    if (0 == (i % 2))
                    {
                        if (i == 10)
                        {
                            mac_dest = mac_dest.Insert(0, mac_src.Substring(i, 2));
                        }
                        else
                        {
                            mac_dest = "-" + mac_dest.Insert(0, mac_src.Substring(i, 2));
                        }
                    }
                }
                return mac_dest;
            }
            catch
            {
                return "";
            }
        }

        /// <summary>
        /// 取得当前页的URL
        /// </summary>
        /// <returns></returns>
        public static string GetNowUrl()
        {
            string url;
            try
            {
                url = System.Web.HttpContext.Current.Request.RawUrl;
            }
            catch
            {
                url = "";
            }
            return url;
        }

        /// <summary>
        /// 获得上一页的URL
        /// </summary>
        /// <returns></returns>
        public static string GetPreviousUrl()
        {
            string url;
            try
            {
                url = System.Web.HttpContext.Current.Request.UrlReferrer.PathAndQuery;
            }
            catch
            {
                url = "";
            }
            return url;
        }
        /// <summary>
        /// 获取当前时间字符串+3位随机数20位（可保证全站唯一）格式为（20090410120023123342）
        /// </summary>
        /// <returns></returns>
        public static string GetNowTimeString()
        {
            return DateTime.Now.ToString("yyyyMMddHHmmssfff") + GetRandomNum(3);
        }
        /// <summary>
        /// 获取 appSeting中的指定键的键值
        /// </summary>
        /// <param name="strKey"></param>
        /// <returns></returns>
        public static string GetConfigAppValue(string strKey)
        {
            return ConfigurationManager.AppSettings[strKey].ToString();
        }
        /// <summary>
        /// 返回指定ConnectionStrings的值
        /// </summary>
        /// <param name="strKey"></param>
        /// <returns></returns>
        public static string GetConfigConValue(string strKey)
        {
            return ConfigurationManager.ConnectionStrings[strKey].ConnectionString;
        }
        /// <summary>
        /// 把一个字符串按照t位长度分割为数组
        /// </summary>
        /// <param name="str"></param>
        /// <param name="t"></param>
        /// <returns></returns>
        public static string[] ArrayListstr(string str, int n)
        {
            string[] result;
            try
            {
                if (n <= 0)
                {
                    n = str.Length;
                }
                int arrynum = 0;
                arrynum = (int)(str.Length / n);
                if (arrynum <= 0)
                {
                    arrynum = 1;
                }
                result = new string[arrynum];
                for (int i = 0; i < arrynum; i++)
                {
                    result[i] = str.Substring(n * i, n);
                }
            }
            catch
            {
                result = new string[1] { "" };
            }
            return result;
        }
    }
}
